<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>图书馆管理系统</h2>
      </template>
      
      <el-form :model="loginForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="loginForm.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginForm.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus' 

export default {
  setup() {
    const store = useStore()
    const router = useRouter()
    const loginForm = ref({
      username: '',
      password: ''
    })

    const handleLogin = async () => {
      try {
        const response = await axios.post('/api/auth/login', loginForm.value)
        const token = response.data.token
        store.commit('setToken', token)
        await store.dispatch('getUserInfo')
        router.push('/')
        ElMessage.success('登录成功')
      } catch (error) {
        ElMessage.error('登录失败')
      }
    }

    return {
      loginForm,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}
</style> 